import {ERR_OK} from "../../api/config";
import {Base64} from 'js-base64'
import {getLyric} from "../../api/song";

//获取需要的数据
export default class Song {
  constructor({id,mid,singer,name,album,duration,image,url}){
    this.id = id
    this.name = name
    this.mid = mid
    this.singer = singer
    this.album = album
    this.duration  =  duration
    this.image = image
    this.filename = `C400${this.mid}.m4a`
    this.url = url
  }

  // getLyric返回的是  promise
  getLyric(){
    if(this.lyric){
      return Promise.resolve(this.lyric)
    }
    return new Promise((resolve, reject) => {
      getLyric(this.mid).then((res)=>{
        if(res.code === ERR_OK){
          // console.log(this.lyric)
          this.lyric = Base64.decode(res.lyric)
          resolve(this.lyric)
        }else{
          reject('no lyric')
        }
      })
    })
  }
}

//封装一个通常的song类，因为每个页面都需要歌曲列表
export function createSong(musicData) {
  return new Song({
    id: musicData.songid,
    mid: musicData.songmid,
    singer: filterSinger(musicData.singer),
    name: musicData.songname,
    album: musicData.albumname,
    duration: musicData.interval,
    image: 'https://y.gtimg.cn/music/photo_new/T002R300x300M000'+musicData.albummid+'.jpg?max_age=2592000',
    // url:'http://dl.stream.qqmusic.qq.com/C400001J5QJL1pRQYB.m4a?guid=8575213511&vkey=2B138E8B22595A926BDE12276D646C62B16EBA60C01427ED4AB51C6251CF3538D37CF17811C2CE900BAA2F1D54CF65DA3DCD6E137C7F8B8B&uin=0&fromtag=38'
    // url:`http://dl.stream.qqmusic.qq.com/http://dl.stream.qqmusic.qq.com/C400000jF0b70x9gDf.m4a?guid=563139015&vkey=CEBB993A0C4FFC42E4AD0A2DB1594C59BC18611CF1E7D0D9DB9E05D1536FB1644E50BCE1F9422A1A2DD21214B376652EF2BE892710EF6F2C&uin=0&fromtag=38`
    // url:'http://dl.stream.qqmusic.qq.com/C400'+musicData.songmid+'.m4a?guid=2888464256&vkey=1452D34C66DBA37DFB8E833A73F07605BE7487440065DBC25CAC7A5EC4C2BFCE96F683B645315475594F2EAD9968266A00270DA3C3D3FCF2&uin=0&fromtag=66 '
    url:'https://api.bzqll.com/music/tencent/url?key=579621905&id=004Cj9tn1vIKop&br=320'
  })
}

function filterSinger(singer) {
  let ret = []
  if (!singer) {
    return ''
  }
  singer.forEach((s) => {
    ret.push(s.name)
  })
  return ret.join('/')
}

export function isValidMusic(musicData) {
  return musicData.songid && musicData.albummid && (!musicData.pay || musicData.pay.payalbumprice === 0)
}

